<?php

namespace model;

use common\Model;

class article_special extends Model
{

	const TABLE = 'article_special';
	protected $DB;
	function __construct($table = self::TABLE)
	{
		$this->DB = parent::db($table);
	}

	private function PostData()
	{
		return [
			'name' => VarFilter($_POST['name']),
			'ico' => VarFilter($_POST['ico']),
			'img_a' => VarFilter($_POST['img_a']),
			'img_b' => VarFilter($_POST['img_b']),
			'img_c' => VarFilter($_POST['img_c']),
			'area' => intval($_POST['area']),
			'url' => VarFilter($_POST['url']),
			'status' => intval($_POST['status']),
			'sort' => intval($_POST['sort'])
		];
	}

	public function FindData()
	{
		return $this->DB->where(['id' => $_GET['id']])->find();
	}

	//获取数据并分页
	public function jsonPageSelect()
	{
		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 15;
		$page = ['num' => $num, 'p' => $p, 'return' => true];

		if (isset($_GET['name']))
			$where['name LIKE'] = '%' . $_GET['name'] . '%';
		else
			$where = '';
		return [
			'data' => $this->DB->where($where)->Page($page)->order('id DESC')->select(),
			'page' => $this->DB->getPage()
		];
	}

	//添加数据
	public function insertData()
	{
		if (empty($_POST['name']))
			return ['status' => 0, 'msg' => '请填写必要数据'];
		$re_key = $this->DB->insert($this->PostData());
		if ($re_key > 0) {
			SqlLog("添加专题 ID:" . $re_key);
			CleanDbCache(self::TABLE);
			return ['status' => 1, 'msg' => '添加成功'];
		} else {
			return ['status' => 0, 'msg' => '数据错误！添加失败'];
		}
	}

	//更新数据
	public function updateData()
	{
		if (empty($_POST['name']))
			return ['status' => 0, 'msg' => '请填写必要数据'];

		if ($this->DB->Where(['id' => $_POST['id']])->Update($this->PostData())) {
			SqlLog("修改专题 ID:" . $_POST['id']);
			CleanDbCache(self::TABLE);
			return ['status' => 1, 'msg' => '修改成功'];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化'];
		}
	}

	//更新排序数据
	public function updateSort()
	{
		if ($this->DB->Where(['id' => $_GET['id']])->Update(['sort' => $_POST['sort']])) {
			SqlLog("修改内容专题排序 ID:" . $_GET['id']);
			CleanDbCache(self::TABLE);
			return  ['status' => 1, 'msg' => '修改成功'];
		} else {
			return  ['status' => 0, 'msg' => '未修改'];
		}
	}

	//设置状态
	public function switchStatus()
	{
		SqlLog("切换专题显示控制 ID:" . $_POST['id']);
		CleanDbCache(self::TABLE);
		return $this->DB->where(['id' => $_POST['id']])->Update(['status' => $_POST['status']]);
	}

	//删除一条数据
	public function deleteOneData()
	{
		if ($this->DB->where(['id' => $_POST['id']])->Delete()) {
			SqlLog("删除专题：" . $_POST['id']);
			return true;
		} else
			return false;
	}
}
